<template>
  <div class="role-dialog">
    <el-dialog :visible.sync="visible">
      <div class="panelWrap role-dialog-content">
        <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
          <div>{{ isEdit ? '修改角色' : '添加角色' }}</div>
          <i class="el-icon-close" @click="handleCloseDialogUpdate" />
        </div>

        <div class="role-content flex flexdc">
          <div class="m-b-10 m-t-40 flexdc flexcenter role-header">
            <div class="role-org flex flexac">
              <span class="role-company">角色所属公司：</span>
              <el-input v-model="form.companyName" class="com-input" readonly @input="handleValueChange" />
              <div>
                <el-button v-if="!isEdit" type="warning" class="comp-select m-l-20 iconfont icon-xuanze" @click="handleSelect">选择公司</el-button>
                <div v-else class="com-select m-l-20" />
              </div>
            </div>

            <div class="roleName m-t-20">
              <span class="roleName-name m-l-20"><span class="mustval">*</span>角色名称：</span>
              <el-input v-model.trim="form.roleName" class="roleName-input" />
            </div>

            <div class="role-admin m-t-20">
              <el-checkbox v-model="form.isAdmin" class="admin-checked" />
              <span class="m-l-10 admin-name">是否管理员</span>
            </div>
            <div class="role-select m-t-40">
              <el-select v-if="form.unitId === 1" v-model="checkSysiId" class="select-system m-b-10" placeholder="请选择系统平台" @change="handleChangeOrg">
                <el-option v-for="item in form.systems" :key="item.sysId" :label="item.sysName" :value="item.sysId" />
              </el-select>

              <el-select v-else v-model="checkSysiId" class="select-system m-b-10" placeholder="请选择系统平台" @change="handleChangeOrg">
                <el-option v-for="item in form.sysIdList" :key="item.sysId" :label="item.sysName" :value="item.sysId" />
              </el-select>
            </div>
          </div>

          <div class="role-main flex flexdc flexac">

            <!-- 树结构 -->
            <div class="role-center">
              <div class="center-tree flex">
                <div class="panelWrap tree-grow m-r-80">
                  <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
                    <div>系统权限</div>
                  </div>
                  <div class="sysTree">
                    <el-tree
                      ref="tree"
                      class="left-tree coTree"
                      :current-node-key="0"
                      :data="setTree"
                      :props="defaultProps"
                      :node-key="NODE_KEY"
                      :default-expanded-keys="[1]"
                      :show-checkbox="true"
                      :highlight-current="true"
                      :default-checked-keys="[0]"
                      @check-change="handleCheckChange"
                    />
                  </div>
                </div>
                <!-- <div class="tree-btn flexcenter">
                  <el-button class="el-icon-caret-right right m-b-20 m-r-15" />
                  <el-button class="el-icon-caret-left left m-r-25" @click="handleLeft" />
                </div> -->

                <div class="panelWrap tree-grow">
                  <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
                    <div>角色权限</div>
                  </div>

                  <div class="roleTree">
                    <el-tree
                      ref="treeRight"
                      class="right-tree coTree"
                      :default-expand-all="true"
                      :current-node-key="NODE_KEY"
                      :data="setTre"
                      :props="defaultProps"
                      :node-key="NODE_KEY"
                      :show-checkbox="true"
                      :highlight-current="true"
                      @node-click="handleNodeClick"
                    />
                  </div>
                </div>
              </div>

              <div class="role-footer">
                <div class="role-find flex flexac m-t-40">
                  <span class="m-l-10">角色查看数据范围：</span>
                  <el-radio-group v-model="form.dataScope" class="find-radio">
                    <el-radio label="本人" />
                    <el-radio label="本机构" />
                    <el-radio label="本机构及其下级机构" />
                  </el-radio-group>
                </div>

                <div class="footer-btn flex flexac flextc m-b-40 m-t-20">
                  <div class="btnBox">
                    <el-button v-if="!isEdit" class="saveBtn btn m-r-20 el-icon-circle-check" @click="handleCreateAdd">保 存</el-button>
                    <el-button v-else class="btn m-r-20 el-icon-circle-check" type="success" @click="handleUpdate">更 新</el-button>
                    <el-button class="btn m-t-30 el-icon-circle-close" type="warning" @click="handleCloseDialog">取 消</el-button>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>
    </el-dialog>

    <CoSelect v-model="coSelectVisible" @update="handleSelectUpdate" />
  </div>

</template>

<script>

// import { createRoleAdd, fetchRoleList, updateRoleArticle } from '@/api/baseInfo/authority/role'
import CoSelect from '@/components/coSelect/index'
// import { fetchResList, fetchDetail } from '@/api/baseInfo/authority/resources'
// import { fetchSystemCompanyId } from '@/api/baseInfo/authority/company'
import { showNotice, formatDateTime, transData } from '@/utils/toolclass'

export default {
  name: 'Role',
  components: { CoSelect },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      allDate: '',
      list: [],
      platData: [],
      platValue: [],
      checkSysiId: '',
      setTre: [],
      roleResources: [],
      roleRightRes: [],
      coSelectVisible: false,
      visible: false,
      dataList: [],
      formOrigin: {
        crtDate: [],
        dataScope: '本人',
        id: 0,
        isAdmin: '',
        isTop: '',
        lstEdtDate: '',
        orgId: '',
        orgName: '',
        resourcesList: [],
        roleName: '',
        roleStatus: '',
        sysIdList: [],
        unitId: '',
        companyName: ''
      },
      form: { ...this.data },
      setTree: [], // tree数据
      NODE_KEY: 'resourceId', // id对应字段
      MAX_LEVEL: 3, // 设定最大层级
      NODE_ID_START: 0, // 新增节点id，逐次递减
      startId: null,
      defaultProps: {// 默认设置
        children: 'children',
        label: 'resourceName'
      },
      initParam: {// 新增参数
        resourceName: '新增节点',
        parentId: 1
        // children: []
      },
      currentNode: {},
      routeArr: [],
      sysIdList: []

    }
  },
  computed: {},
  watch: {
    visible(v) {
      this.$emit('input', v)
    },
    value(v) {
      if (this.form.id === 0) {
        this.form = { ...this.formOrigin }
      }
      this.visible = v
    },
    data(v) {
      if (v.id === 0) {
        this.form = { ...this.formOrigin }
      } else {
        this.form = { ...v }
      }
    }
  },
  created() {
    this.startId = this.NODE_ID_START
  },
  methods: {

    handleLeft() {
      const resId = this.roleRightRes.forEach(item => {
        return item.resourceId
      })
      this.roleResources = this.roleResources.filter((item, i) => {
        if (item.resourceId === resId) {
          this.roleResources.splice(i, 1)
        }
      })
    },
    handleCheckChange() {
      const checkParent = this.$refs.tree.getHalfCheckedKeys()
      const ParentArr = []
      checkParent.forEach((item1) => {
        this.allDate.forEach((item2) => {
          if (item1 !== 1 && item1 === item2.resourceId) {
            if (item2.children) {
              delete item2.children
            }
            ParentArr.push(item2)
          }
        })
      })
      // this.roleResources = this.$refs.tree.getCheckedNodes()

      let resArr = this.$refs.tree.getCheckedNodes()
      resArr = resArr.concat(ParentArr)
      // console.log(resArr)
      let newArr = []
      const getArr = (res) => {
        res.forEach((item) => {
          // console.log('item')
          // console.log(item)
          newArr.push(item)
          if (item.children) {
            getArr(item.children)
          }
        })
      }
      getArr(resArr)
      // console.log('新数组')

      newArr = Array.from(new Set(newArr))

      newArr = newArr.map(function(value, index) {
        if (value.children) {
          delete value.children
        }
        return value
      })

      const resourcesArr = newArr.map(function(value, index) {
        value = {
          resourceId: value.resourceId,
          sysId: value.sysId
        }
        return value
      })

      this.sysIdList = resourcesArr
      this.setTre = transData(newArr, 'resourceId', 'parentId') //
    },
    // 查询所有公司弹窗
    handleSelect() {
      this.coSelectVisible = true
    },
    // 公司信息更新回调
    handleSelectUpdate(row) {
      this.form.companyName = row.companyName
      this.form.companyId = row.companyId
      this.handleValueChange(row.companyId)
    },
    // 根据公司获取公司能够使用的系统
    handleValueChange(companyId) {
      fetchSystemCompanyId(companyId).then(res => {
        this.form.sysIdList = res.data
        this.checkSysiId = res.data[0].sysId
        this.handleChangeOrg(this.checkSysiId)
      })
    },
    // 获取公司能够使用的系统下的所有权限
    handleChangeOrg(val) {
      this.checkSysiId = val
      fetchResList(val).then(res => {
        // console.log(res.data)
        this.allDate = res.data
        this.setTree = transData(res.data, 'resourceId', 'parentId')
        // console.log(this.setTree)
        this.platData = res.data.map(item => item)
      })
    },
    getMenuDetail(resourceId, systemId) {
      this.dataList = []
      fetchDetail(resourceId, systemId).then((res) => {
        this.dataList.push(res.data)
      })
    },
    handleNodeClick(res) {
      this.getMenuDetail(res.resourceId, res.sysId)
    },
    handleUpdate() {
      const resourcesList = this.sysIdList.map(val => {
        val = {
          roleId: this.form.id,
          sysId: val.sysId,
          resourceId: val.resourceId
        }
        return val
      })
      const params = {
        // crtDate: this.form.crtDate,
        id: this.form.id,
        unitId: this.form.unitId,
        orgId: this.form.orgId,
        isAdmin: !!this.form.isAdmin,
        roleStatus: this.form.roleStatus === '启用' ? 1 : 2,
        dataScope: this.form.dataScope === '本人' ? 1 : this.form.dataScope === '本机构' ? 2 : 3,
        sysIdList: [this.checkSysiId],
        // lstEdtDate: formatDateTime().ymdhm,
        roleName: this.form.roleName,
        orgName: this.form.orgName,
        companyName: this.form.companyName,
        resourcesList: resourcesList
      }
      updateRoleArticle(params).then(res => {
        if (res.code === '000000') {
          showNotice('success', '提示', '保存成功!')
          this.$emit('handleRefresh')
          this.$emit('handleCloseDialog')
        } else {
          // showNotice('error', '提示', res.msg)
        }
      })
    },
    handleCreateAdd() {
      const params = {
        unitId: parseInt(this.form.companyId),
        orgId: this.checkSysiId,
        sysIdList: [this.checkSysiId],
        orgName: this.form.orgName,
        roleName: this.form.roleName,
        isAdmin: !!this.form.isAdmin,
        dataScope: this.form.dataScope === '本人' ? 1 : this.form.dataScope === '本机构' ? 2 : 3,
        resourcesList: this.sysIdList
      }
      createRoleAdd(params).then(res => {
        if (res.code === '000000') {
          showNotice('success', '提示', '添加成功!')
          this.$emit('handleRefresh', { unitId: parseInt(this.form.companyId), companyName: this.form.companyName })
          this.$emit('handleCloseDialog')
        } else {
          // showNotice('error', '提示', res.msg)
        }
      })
    },
    getRoleList(params) {
      fetchRoleList(params.unitId, params.roleName).then((res) => {
        if (res.code === '000000') {
          this.dataList = res.data
        }
      })
    },
    handleInput(_node, _data) { // 修改节点
      // 退出编辑状态
      if (_node.isEdit) {
        this.$set(_node, 'isEdit', false)
      }
    },
    handleCloseDialog() {
      this.$emit('handleCloseDialog')
    },

    handleExportExcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/excel/Export2Excel')
        const tHeader = ['系统ID', '资源图标', '父资源', '资源ID', '资源名称', '资源顺序', '资源类型', '资源链接']
        const filterVal = ['sysId', 'iconUrl', 'parentId', 'resourceId', 'orgName', 'resourceSort', 'resourceType', 'resourceUrl']
        const data = this.formatJson(filterVal, this.dataList)
        export_json_to_excel(tHeader, data, '系统平台权限资源表(' + formatDateTime().ymd) + ')'
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleCloseDialogUpdate() {
      this.visible = !this.visible
    }
  }
}
</script>

<style lang="scss">
@import "@/styles/public.scss";
.role-dialog {
  .role-dialog-content {
    width: 860px;
    margin: 200px 0 0 200px;
  }
  .panelWrap {
    background: #ffffff;
    .role-content {
      .role-header {
        .role-select {
          margin-left: -280px;
        }
        .roleName {
          margin-left: -125px;
        }
        .role-admin {
          margin-left: -104px;
        }
        .role-org {
          .com-select {
            width: 100px;
            height: 40px;
          }
        }
      }
      .role-main {
        .role-center {
          .center-tree {
            .tree-grow {
              .tree-btn {}
              .sysTree {
                .left-tree {
                  .el-tree-node .el-checkbox .el-checkbox__inner {
                    display: block !important;
                  }
                }
              }
              .coTree {
                width: 196px;
                height: 300px;
                overflow: auto;
              }
            }
          }
          .role-footer {}
        }
      }
    }
  }
}
</style>
